import axios from "axios"
import { Message, MessageBox } from "element-ui"
import { getToken, setToken, removeToken } from "@/utils/auth"
import cache from "@/utils/cache"
import { updateToken } from "@/api/user"
import qs from "qs"


// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 35000 // request timeout
})

// axios.defaults.withCredentials = true; // 让ajax携带cookie
// request interceptor
service.interceptors.request.use((config) => {
    // do something before request is sent
    if (getToken()) {
      config.headers["token"] = getToken()
    }
    // if (config.qs) {
    config.headers["Content-Type"] = "application/x-www-form-urlencoded"
    // config.headers["Content-Type"] = "multipart/form-data"
    // }

    if (config.method === "post" && config.data) {
      config.data = qs.stringify(config.data)

      const requestObj = {
        url: config.url,
        data: typeof config.data === "object" ? qs.stringify(config.data) : config.data,
        time: new Date().getTime()
      }

      const sessionObj = cache.session.getJSON("sessionObj")
      if (sessionObj === undefined || sessionObj === null || sessionObj === "") {
        cache.session.setJSON("sessionObj", requestObj)
      } else {
        const s_url = sessionObj.url
        const s_data = sessionObj.data
        const s_time = sessionObj.time
        const interval = 0
        if (s_data === requestObj.data && requestObj.time - s_time < interval && s_url === requestObj.url) {
          const message = "数据正在处理，请勿重复提交"
          console.warn(`[${s_url}]: ` + message)
          return Promise.reject(new Error(message))
        } else {
          cache.session.setJSON("sessionObj", requestObj)
        }
      }
    }

    if (config.url.includes("upload")) {
      config.headers["Content-Type"] = "multipart/form-data"
      config.headers["token"] = getToken()
    }
    return config
  },
  (error) => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use((response) => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.

    if (res.status !== '200') {
      Message({
        message: res.message || "Error",
        type: "error",
        duration: 3 * 1000
      })
      return res
    }

    if (response.config.url.endsWith("/user/queryMessageByProjectCode")) {
      // 获取登录设置,不走token
      return res
    }

    let exp
    if (res.object && res.object.exp) {
      exp = res.object.exp
    } else {
      exp = window.sessionStorage.getItem("exp") || 0
    }
    // const exp = window.sessionStorage.getItem("exp")
    const timestamp = new Date().getTime()

    if ((exp - timestamp) > 0 && (exp - timestamp) < 5 * 60 * 1000) {
      // 0 - 30万毫秒
      updateToken().then(res => {
        const {object} = res
        setToken(object.token)
        sessionStorage.setItem("exp", object.exp)
      })
      return res
    } else if ((exp - timestamp) < 0) {
      removeToken()
      return Promise.reject("无效的会话，或者会话已过期，请重新登录。")
    } else {
      return res
    }
  },
  (error) => {
   let aa = "";
    if(error.toString().indexOf("404") != -1){
      aa = "404"
    } else if(error.toString().indexOf("401") != -1){
      aa = "401"
    } else if(error.toString().indexOf("403") != -1){
      aa = "403"
      removeToken();
    } else {
      aa = "服务器维护升级中"
    }
    Message({
      message: aa,
      type: "warning",
      duration: 5 * 1000
    })
    if(aa == "403"){
      location.href = '/';
    }
    // error.response.config.url = error.response.config.url.split('/dev-api')[1]
    // service(error.response.config)
    // return Promise.reject(error)
    // }

    return Promise.reject(error)
  }
)

export default service
